﻿using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Launcher
{
    internal static class LauncherHelper
    {
        private static readonly JsonSerializerOptions _jsonOptions = new()
        {
            PropertyNameCaseInsensitive = true,
            Converters = { new JsonStringEnumConverter() },
            ReadCommentHandling = JsonCommentHandling.Skip,
            AllowTrailingCommas = true
        };

        /// <summary>
        /// 从默认配置文件加载程序集加载参数
        /// </summary>
        public static IEnumerable<AssemblyLoaderParameters> LoadAssemblyLoaderParameters()
        {
            var configPath = GetDefaultConfigPath();
            return LoadAssemblyLoaderParameters(configPath);
        }

        /// <summary>
        /// 从指定路径加载程序集加载参数
        /// </summary>
        public static IEnumerable<AssemblyLoaderParameters> LoadAssemblyLoaderParameters(string configPath)
        {
            if (!File.Exists(configPath))
            {
                throw new FileNotFoundException($"配置文件不存在: {configPath}");
            }

            try
            {
                var jsonText = File.ReadAllText(configPath);
                var saveInfos = JsonSerializer.Deserialize<List<AssemblyLoaderParametersSaveInfo>>(jsonText, _jsonOptions)
                    ?? throw new InvalidOperationException("配置文件内容为空或无效");

                return saveInfos.Select(saveInfo =>
                {
                    return new AssemblyLoaderParameters(
                       saveInfo.AssemblyLoadContextName ?? string.Empty,
                       saveInfo.AssemblyDirectory ?? string.Empty,
                       saveInfo.EntryAssemblyFile ?? string.Empty,
                       saveInfo.EntryType ?? string.Empty,
                       saveInfo.ThreadApartmentState,
                       saveInfo.CommandLineArgs);
                });
            }
            catch (JsonException ex)
            {
                throw new InvalidOperationException($"配置文件解析失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 获取默认配置文件路径
        /// </summary>
        public static string GetDefaultConfigPath()
        {
            return Path.Combine(AppContext.BaseDirectory, "launcher.json");
        }
    }
}